const remote = window.require('@electron/remote');
const electron = window.require('electron');
const { BrowserWindow } = remote;

import vueWindowConfig from '../../config/vueWindow.config.js';

let windows = {};

export default {
  remote,
  electron,
  render: {
    send(channel, ...args) {
      return electron.ipcRenderer.send(channel, ...args); // 渲染进程发送
    },
  },
  main: {
    on(channel, listener) {
      return remote.ipcMain.on(channel, listener); // 主进程监听
    },
    closeWindow(name) {
      delete windows[name].close();
    },
    getWindow(name) {
      return windows[name];
    },
    createWindow(config, url, divConfig) {
      const basicConfig = {
        // 默认配置
        width: 800,
        height: 600,
        webPreferences: {
          contextIsolation: false,
          nodeIntegration: true,
          enableRemoteModule: true,
          nodeIntegrationInWorker: true,
        },
        show: false,
        backgroundColor: '#efefef',
      };
      const finalConfig = { ...basicConfig, ...config }; // 混合配置
      windows[divConfig.name] = new BrowserWindow(finalConfig); // 新建窗口
      const isDevTool = divConfig.isDevTool || vueWindowConfig.isDevTool;
      if (isDevTool) {
        windows[divConfig.name].webContents.openDevTools(); // 是否开启窗口调试
      }
      windows[divConfig.name].loadURL(url); // 加载页面路径
      windows[divConfig.name].once('ready-to-show', () => {
        windows[divConfig.name].show(); // 准备完成再显示
      });
      // 窗口关闭操作
      windows[divConfig.name].on('close', () => {
        delete windows[divConfig.name]; // 窗口对象列表移除窗口
      });
    },
    chooseDir(title) {
      return remote.dialog.showOpenDialogSync(null, {
        title,
        properties: ['openDirectory'],
      });
    },
    chooseFile(title, filters) {
      return remote.dialog.showOpenDialogSync(null, {
        title,
        filters,
        properties: ['openFile'],
      });
    },
  },
};
